package com.uls.ldcm.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.uls.common.core.domain.entity.SysUser;
import com.uls.common.utils.DateUtils;
import com.uls.common.utils.SecurityUtils;
import com.uls.ldcm.domain.Salaryrecords;
import com.uls.ldcm.domain.Salaryschemes;
import com.uls.ldcm.domain.vo.TaskCommentVo;
import com.uls.ldcm.service.ISalaryrecordsService;
import com.uls.ldcm.service.ISalaryschemesService;
import com.uls.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.ldcm.mapper.SalarypaymentsMapper;
import com.uls.ldcm.domain.Salarypayments;
import com.uls.ldcm.service.ISalarypaymentsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 薪资发放管理Service业务层处理
 * 
 * @author gw
 * @date 2024-11-11
 */
@Service
public class SalarypaymentsServiceImpl implements ISalarypaymentsService 
{
    @Autowired
    private SalarypaymentsMapper salarypaymentsMapper;

    @Autowired
    private ISalaryschemesService salaryschemesService;



    @Autowired
    private ISalaryrecordsService salaryrecordsService;


    @Autowired
    private RuntimeService runtimeService;


    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询薪资发放管理
     * 
     * @param paymentId 薪资发放管理主键
     * @return 薪资发放管理
     */
    @Override
    public Salarypayments selectSalarypaymentsByPaymentId(Long paymentId)
    {
        return salarypaymentsMapper.selectSalarypaymentsByPaymentId(paymentId);
    }

    /**
     * 查询薪资发放管理列表
     * 
     * @param salarypayments 薪资发放管理
     * @return 薪资发放管理
     */
    @Override
    public List<Salarypayments> selectSalarypaymentsList(Salarypayments salarypayments)
    {
        return salarypaymentsMapper.selectSalarypaymentsList(salarypayments);
    }

    @Override
    public List<Salarypayments> selectSalarypaymentsListByContractId(Long contractId) {

        return salarypaymentsMapper.selectSalarypaymentsListByContractId(contractId);
    }

    /**
     * 新增薪资发放管理
     * 
     * @param salarypayments 薪资发放管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSalarypayments(Salarypayments salarypayments)
    {
        salarypayments.setCreatedAt(DateUtils.getNowDate());
        salarypayments.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        BigDecimal overtimeHours=salarypayments.getOvertimeHours();
        Salaryschemes salaryschemes = salaryschemesService.selectSalaryschemesByLaborerId(salarypayments.getLaborerId());
        BigDecimal overPay = overtimeHours.multiply(salaryschemes.getOvertimePay());
        salarypayments.setAmount(salaryschemes.getBasicSalary().add(overPay).add(salaryschemes.getBonus()).add(salaryschemes.getAllowances()));
        salarypayments.setBasicSalary(salaryschemes.getBasicSalary());
        salarypayments.setOvertimePay(salaryschemes.getOvertimePay());
        salarypayments.setBonus(salaryschemes.getBonus());
        salarypayments.setAllowances(salaryschemes.getAllowances());
        salarypayments.setOvertimeHours(overtimeHours);
        int result = salarypaymentsMapper.insertSalarypayments(salarypayments);
        return result;
    }

    /**
     * 修改薪资发放管理
     * 
     * @param salarypayments 薪资发放管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSalarypayments(Salarypayments salarypayments)
    {
        salarypayments.setUpdatedAt(DateUtils.getNowDate());
        salarypayments.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        BigDecimal overtimeHours=salarypayments.getOvertimeHours();
        BigDecimal overPay = overtimeHours.multiply(salarypayments.getOvertimePay());
        salarypayments.setAmount(salarypayments.getBasicSalary().add(overPay).add(salarypayments.getBonus()).add(salarypayments.getAllowances()));
        int result = salarypaymentsMapper.updateSalarypayments(salarypayments);
        return result;
    }

    /**
     * 批量删除薪资发放管理
     * 
     * @param paymentIds 需要删除的薪资发放管理主键
     * @return 结果
     */
    @Override
    public int deleteSalarypaymentsByPaymentIds(Long[] paymentIds)
    {
        return salarypaymentsMapper.deleteSalarypaymentsByPaymentIds(paymentIds);
    }

    /**
     * 删除薪资发放管理信息
     * 
     * @param paymentId 薪资发放管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSalarypaymentsByPaymentId(Long paymentId)
    {
        return salarypaymentsMapper.deleteSalarypaymentsByPaymentId(paymentId);
    }

    @Transactional
    @Override
    public int submit(Long paymentId, Long userId) {
        Salarypayments salarypayments = salarypaymentsMapper.selectSalarypaymentsByPaymentId(paymentId);
        String processDefiKey = "LbSalaryTask";
        Map<String, Object> variables = new HashMap<>();

        if (salarypayments.getStatus() == 0) {
            variables.put("inputUser1",userId);
            variables.put("inputUser2",128); // 主任的编号
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            if (pi == null || pi.getProcessInstanceId() == null) {
                throw new RuntimeException("流程实例启动失败");
            }
            salarypayments.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));
            salarypayments.setStatus(2); // 状态(0-未提交，1-打回，2-主任审核，3-已完成,4-院长审批）

            TaskQuery taskQuery = taskService.createTaskQuery();
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();

            if (list.isEmpty()) {
                throw new RuntimeException("任务列表为空");
            }

            Task task = list.get(0);
            taskService.complete(task.getId());

            return salarypaymentsMapper.updateSalarypayments(salarypayments);
        } else {
            Long flowInstantId = salarypayments.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId("" + flowInstantId)
                    .list();
            variables.put("inputUser2",128);
            Task task = list.get(0);
            taskService.complete(task.getId(),variables);
            salarypayments.setStatus(2);

            return salarypaymentsMapper.updateSalarypayments(salarypayments);
        }
    }

    @Override
    @Transactional
    public List<Salarypayments> noFinishTask(Long userId, String processDefinitionKey, Salarypayments salarypayments) {
        ArrayList<Salarypayments> listSalarypayments = new ArrayList<>();
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefinitionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("申请工资发放")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    salarypayments.setFlowInstantId(flowInstanceId);
                    Salarypayments salarypayments1 = salarypaymentsMapper.selectSalarypaymentsList(salarypayments).get(0);
                    if(salarypayments1 != null){
                        listSalarypayments.add(salarypayments1);
                    }
                }
            }
        }
        return listSalarypayments;
    }

    @Override
    @Transactional
    public List<TaskCommentVo> getTaskCommentVoList(Long flowInstantId) {
        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();
        List<Comment> list=new ArrayList<>();
        //从历史批注中取数据
        list= taskService.getProcessInstanceComments(""+flowInstantId);
        for(Comment comment:list){
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(comment.getFullMessage());
            SysUser user = userService.selectUserById(Long.parseLong(comment.getUserId()));
            taskCommentVo.setUserName(user.getUserName());
            List<HistoricTaskInstance> hist = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId("" + flowInstantId)
                    .taskId(comment.getTaskId())
                    .list();
            if(hist!=null && hist.size()>0){
                HistoricTaskInstance hti = hist.get(0);
                taskCommentVo.setTaskKeyId(hti.getTaskDefinitionKey());
                taskCommentVo.setTaskName(hti.getName());
            }
            taskCommentVoList.add(taskCommentVo);
        }
        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();
        for(int i=taskCommentVoList.size()-1;i>=0;i--){
            TaskCommentVo temp = taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }
        return taskCommentVoListSort;
    }

    @Override
    @Transactional
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Salarypayments salarypayments,Integer manner) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery.
                processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<>();
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if(task.getName().equals("财务部验证工资数据")){
                    if (agree == 1) {
                        params.put("inputUser3",139);
                        salarypayments.setStatus(4);
                    }else {
                        salarypayments.setStatus(1);
                        params.put("inputUser1",1);
                    }
                    params.put("pass1",agree);
                }else if(task.getName().equals("院长审批")){
                    if (agree == 1) {
                        params.put("inputUser4",140);
                        params.put("pass2",2);
                        salarypayments.setStatus(2);
                    }else {
                        if(manner==0){
                            params.put("pass2",0);
                            params.put("inputUser1",1);
                        }else {
                            params.put("pass2",1);
                            params.put("inputUser2",128);
                        }
                        salarypayments.setStatus(1);
                    }
                }else if(task.getName().equals("打印工资条并发工资")){
                    if(agree==1){
                        Salaryrecords salaryrecords = new Salaryrecords();
                        salaryrecords.setLaborerId(salarypayments.getLaborerId());
                        salaryrecords.setSalaryMonth(salarypayments.getPaymentDate());
                        salaryrecords.setBasicSalary(salarypayments.getBasicSalary());
                        salaryrecords.setBonus(salarypayments.getBonus());
                        salaryrecords.setAllowances(salarypayments.getAllowances());
                        BigDecimal overtimeHours=salarypayments.getOvertimeHours();
                        BigDecimal overPay = overtimeHours.multiply(salarypayments.getOvertimePay());
                        salaryrecords.setOvertimeHours(overtimeHours);
                        salaryrecords.setOvertimePay(overPay);
                        salaryrecords.setTotalSalary(salarypayments.getAmount());
                        salaryrecordsService.insertSalaryrecords(salaryrecords);
                        salarypayments.setStatus(3);
                    }else {
                        salarypayments.setStatus(1);
                        params.put("inputUser2",128);
                    }
                    params.put("pass3",agree);
                }
                updateSalarypayments(salarypayments);
                Authentication.setAuthenticatedUserId(userId.toString());
                if(comment!=null){
                    taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                }else {
                    taskService.addComment(task.getId(), task.getProcessInstanceId(), "未填写审批意见");
                }
                taskService.complete(task.getId(), params);
            }
        }
    }

    @Override
    public List<Salarypayments> finishTask(Long userId, String processDefinitionKey, Salarypayments salarypayments) {
        List<Salarypayments> listFinishSalarypayments = new ArrayList<>();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefinitionKey)
                .processFinished()
                .list();
        if(list!=null && list.size() > 0){
            for(HistoricTaskInstance temp : list){
                if(!temp.getName().equals("申请工资发放")){
                    long flowInstantId = Long.parseLong(temp.getProcessInstanceId());
                    salarypayments.setFlowInstantId(flowInstantId);
                    List<Salarypayments> salarypaymentsList = salarypaymentsMapper.selectSalarypaymentsList(salarypayments);
                    if(salarypaymentsList.get(0)!=null)
                    listFinishSalarypayments.add(salarypaymentsList.get(0));
                }
            }
        }
        //去重
        List<Salarypayments> listFinishStudent1 = new ArrayList<>(new HashSet<>(listFinishSalarypayments));

        return listFinishStudent1;
    }

}
